package network.websocket;

import application.RequestHandlerBus;
import application.UserLoggedManager;
import contracts.ContractTypeSerializer;
import eventbus.PageEventBus;
import eventbus.PageEvents;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.log4j.Logger;
import util.ChannelHelper;

/**
 * 文本类型的websockets消息处理器
 * 在netty下文本类型消息为TextWebSocketFrame类型
 *
 * @author wyl
 */
public class TextWebsocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private final Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        String id = ctx.channel().id().asLongText();
        String msg = frame.text();
        PageEventBus.publish(PageEvents.ADD_TRAFFIC_EVENT);
        System.out.println("id:" + id + " 发来消息" + msg);
        //按照约定通信传输使用json字符串并且是WSDto的json类型
        WSDto wsDto = WSDtoConverter.readJsonToWSDto(msg);
        //WSDto转成请求实体
        Object requestObj = ContractTypeSerializer.deserialize(wsDto.typeName, wsDto.dataJson);
        //请求处理器总线处理客户端请求
        RequestHandlerBus.handleRequest(requestObj, ctx.channel());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("出现异常", cause);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端加入连接：" + ctx.channel());
        ChannelManager.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端断开连接：" + ctx.channel());
        ChannelManager.removeChannel(ctx.channel());
        UserLoggedManager.logout(ChannelHelper.getConnId(ctx.channel()));
    }
}

